<script setup lang="ts">
const route = useRoute()
const id = route.params.id as string

const { data, refresh } = await useHttpFetch(`/api/scheduler/tasks/${id}`)
const task = computed(() => (data.value as any)?.task)
const recentExecutions = computed(() => (data.value as any)?.recentExecutions ?? [])

async function handleTrigger() {
  await $fetch(`/api/scheduler/tasks/${id}/trigger`, { method: "POST" })
}

async function handleToggle() {
  if (!task.value) return
  await $fetch(`/api/scheduler/tasks/${id}/toggle`, {
    method: "POST",
    body: { enabled: !task.value.enabled },
  })
  refresh()
}

function statusClass(status: string): string {
  switch (status) {
    case "success": return "status-success"
    case "failed": return "status-failed"
    case "running": return "status-running"
    default: return "status-pending"
  }
}

function timeAgo(ts: number | string): string {
  const t = typeof ts === "string" ? new Date(ts).getTime() : ts
  const diff = Date.now() - t
  if (isNaN(diff)) return ""
  const mins = Math.floor(diff / 60000)
  if (mins < 1) return "just now"
  if (mins < 60) return `${mins}m ago`
  const hours = Math.floor(mins / 60)
  if (hours < 24) return `${hours}h ago`
  return `${Math.floor(hours / 24)}d ago`
}
</script>

<template>
  <div class="task-detail-page">
    <div class="back-link">
      <NuxtLink to="/admin/scheduler">
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
          <path d="M15 18l-6-6 6-6" stroke-linecap="round" stroke-linejoin="round" />
        </svg>
        返回任务列表
      </NuxtLink>
    </div>

    <div v-if="task" class="task-content">
      <!-- Task header -->
      <header class="task-header">
        <div class="task-info">
          <h1 class="task-title">{{ task.name }}</h1>
          <p class="task-meta">
            <code class="cron-code">{{ task.cronExpression }}</code>
            <span class="meta-sep">&middot;</span>
            <span :class="['type-badge', task.type === 'function' ? 'type-function' : 'type-http']">
              {{ task.type }}
            </span>
          </p>
        </div>
        <div class="task-actions">
          <button class="btn-secondary" @click="handleTrigger">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
              <polygon points="5 3 19 12 5 21 5 3" fill="currentColor" />
            </svg>
            立即触发
          </button>
          <button class="btn-secondary" @click="handleToggle">
            {{ task.enabled ? '暂停' : '恢复' }}
          </button>
        </div>
      </header>

      <!-- Task config -->
      <section class="config-section">
        <h2 class="section-title">配置信息</h2>
        <div class="config-card">
          <dl class="config-grid">
            <div class="config-item">
              <dt>Type</dt>
              <dd>{{ task.type }}</dd>
            </div>
            <template v-if="task.type === 'function'">
              <div class="config-item">
                <dt>Function</dt>
                <dd>{{ task.functionName }}</dd>
              </div>
              <div class="config-item config-item-full">
                <dt>Payload</dt>
                <dd><code class="payload-code">{{ task.functionPayload || '(none)' }}</code></dd>
              </div>
            </template>
            <template v-if="task.type === 'http'">
              <div class="config-item">
                <dt>Method</dt>
                <dd>{{ task.httpMethod }}</dd>
              </div>
              <div class="config-item config-item-full">
                <dt>URL</dt>
                <dd><code class="payload-code">{{ task.httpUrl }}</code></dd>
              </div>
            </template>
            <div class="config-item">
              <dt>补录执行</dt>
              <dd>{{ task.catchUp ? 'Yes' : 'No' }}</dd>
            </div>
            <div class="config-item">
              <dt>重试次数</dt>
              <dd>{{ task.maxRetries }}</dd>
            </div>
            <div class="config-item">
              <dt>超时时间</dt>
              <dd>{{ task.timeoutSeconds }}s</dd>
            </div>
            <div class="config-item">
              <dt>创建时间</dt>
              <dd>{{ new Date(task.createdAt).toLocaleString() }}</dd>
            </div>
          </dl>
        </div>
      </section>

      <!-- Execution history -->
      <section class="exec-section">
        <h2 class="section-title">最近执行记录</h2>
        <div class="exec-card">
          <div v-if="recentExecutions.length === 0" class="empty-state">
            暂无执行记录
          </div>
          <div v-else class="exec-list">
            <div v-for="log in recentExecutions" :key="log.id" class="exec-item">
              <span :class="['exec-status', statusClass(log.status)]">
                {{ log.status }}
              </span>
              <span class="exec-time">
                {{ timeAgo(log.startedAt) }}
              </span>
              <span v-if="log.resultSummary" class="exec-result">
                {{ log.resultSummary }}
              </span>
            </div>
          </div>
        </div>
      </section>
    </div>

    <div v-else-if="data" class="not-found">
      任务未找到
    </div>
  </div>
</template>

<style scoped>
.task-detail-page {
  padding: 40px;
}

.back-link a {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  color: var(--color-muted);
  text-decoration: none;
  font-size: 13px;
  font-weight: 500;
  transition: color 0.15s ease;
}

.back-link a:hover {
  color: var(--color-ink);
}

.back-link svg {
  width: 14px;
  height: 14px;
}

.task-content {
  margin-top: 24px;
}

.task-header {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  margin-bottom: 32px;
}

.task-title {
  font-family: var(--font-display);
  font-size: 28px;
  font-weight: 400;
  color: var(--color-ink);
  letter-spacing: -0.3px;
  margin: 0 0 8px 0;
}

.task-meta {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: var(--color-muted);
  margin: 0;
}

.cron-code {
  font-family: 'JetBrains Mono', monospace;
  font-size: 13px;
  background: var(--color-surface-soft);
  padding: 2px 8px;
  border-radius: 4px;
}

.meta-sep {
  color: var(--color-hairline);
}

.type-badge {
  padding: 3px 10px;
  border-radius: 9999px;
  font-size: 12px;
  font-weight: 500;
}

.type-function {
  background: rgba(93, 184, 166, 0.15);
  color: var(--color-accent-teal);
}

.type-http {
  background: rgba(232, 165, 90, 0.15);
  color: var(--color-accent-amber);
}

.task-actions {
  display: flex;
  gap: 10px;
}

.btn-secondary {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  padding: 10px 16px;
  background: var(--color-surface-card);
  color: var(--color-ink);
  border: 1px solid var(--color-hairline);
  border-radius: 8px;
  font-size: 13px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.15s ease;
}

.btn-secondary:hover {
  background: var(--color-surface-soft);
  border-color: var(--color-hairline-soft);
}

.btn-secondary svg {
  width: 14px;
  height: 14px;
}

.section-title {
  font-size: 12px;
  font-weight: 600;
  color: var(--color-muted);
  text-transform: uppercase;
  letter-spacing: 0.05em;
  margin: 0 0 12px 0;
}

.config-section {
  margin-bottom: 32px;
}

.config-card {
  background: var(--color-surface-card);
  border-radius: 12px;
  padding: 20px;
}

.config-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.config-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.config-item-full {
  grid-column: 1 / -1;
}

.config-item dt {
  font-size: 12px;
  color: var(--color-muted);
  font-weight: 500;
}

.config-item dd {
  font-size: 14px;
  color: var(--color-ink);
  margin: 0;
}

.payload-code {
  font-family: 'JetBrains Mono', monospace;
  font-size: 13px;
  background: var(--color-surface-soft);
  padding: 4px 10px;
  border-radius: 6px;
  word-break: break-all;
}

.exec-section {
  margin-bottom: 32px;
}

.exec-card {
  background: var(--color-surface-card);
  border-radius: 12px;
  overflow: hidden;
}

.empty-state {
  padding: 32px;
  text-align: center;
  font-size: 14px;
  color: var(--color-muted-soft);
}

.exec-list {
  border-top: 1px solid var(--color-hairline);
}

.exec-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 14px 16px;
  border-bottom: 1px solid var(--color-hairline);
}

.exec-item:last-child {
  border-bottom: none;
}

.exec-status {
  display: inline-block;
  padding: 3px 10px;
  border-radius: 9999px;
  font-size: 12px;
  font-weight: 500;
  min-width: 70px;
  text-align: center;
}

.status-success {
  background: rgba(93, 184, 166, 0.15);
  color: var(--color-accent-teal);
}

.status-failed {
  background: rgba(198, 69, 69, 0.12);
  color: #c64545;
}

.status-running {
  background: rgba(232, 165, 90, 0.15);
  color: var(--color-accent-amber);
}

.status-pending {
  background: var(--color-hairline);
  color: var(--color-muted);
}

.exec-time {
  font-size: 13px;
  color: var(--color-muted);
  min-width: 70px;
}

.exec-result {
  font-size: 13px;
  color: var(--color-body);
  flex: 1;
}

.not-found {
  margin-top: 40px;
  font-size: 15px;
  color: var(--color-muted-soft);
}

@media (max-width: 640px) {
  .task-detail-page {
    padding: 24px;
  }

  .task-header {
    flex-direction: column;
    gap: 16px;
  }

  .task-actions {
    width: 100%;
  }

  .btn-secondary {
    flex: 1;
    justify-content: center;
  }

  .config-grid {
    grid-template-columns: 1fr;
  }

  .config-item-full {
    grid-column: 1;
  }
}
</style>